import React, { Component } from 'react';
import { Card } from 'material-ui/Card';
import Avatar from 'material-ui/Avatar';
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import { List, ListItem } from 'material-ui/List';
import { grey400 } from 'material-ui/styles/colors';
import CircularProgress from 'material-ui/CircularProgress';
import CommunicationChatBubble from 'material-ui/svg-icons/communication/chat-bubble';

import Masonry from 'react-masonry-component';
import InfiniteScroll from 'react-infinite-scroller';

import Chat from '../Chat';
import CONFIG from '../../config';
import { parseJSON, getMethod, postJsonMethod } from '../../redux/Helper';

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actionCreators from '../../redux/actions/MessageActions';

class Friends extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      total: 0,
      nextPageUrl: null,
      isInfiniteLoading: true,
    };
  }

  componentWillMount() {
    this.initFetch();
  }

  componentDidMount() {
    this.chat = this.props.socket;
  }

  /**
   * 初始化获取用户列表
   */
  initFetch = () => {
    let url = `${CONFIG.apiHost}/api/friends?token=${this.props.token}`;
    fetch(url, getMethod)
    .then(parseJSON)
    .then(res => {
      if (res.next_page_url) {
        this.setState({isInfiniteLoading: true})
      }else{
        this.setState({isInfiniteLoading: false})
      }
      this.setState({
        data: res.data,
        total: res.total,
        nextPageUrl: res.next_page_url
      });
    });
  };

  elementInfiniteLoad() {
    return (
      <div className="center-block" style={{width: 32}}>
        <CircularProgress 
          size={32} 
          style={{margin: 8}} 
          thickness={3} 
        /> 
      </div>
    );
  }

  handleInfiniteLoad = () => {
    if (this.state.nextPageUrl) {
      let arr = this.state.data;

      let request = '&token='+this.props.token;
      let url = this.state.nextPageUrl + request;

      fetch(url, getMethod)
      .then(parseJSON)
      .then(res => {
        setTimeout(() => {
          this.setState({
            nextPageUrl: res.msg.next_page_url,
            data: arr.concat(res.msg.data)
          });
        }, 500)
      })
    }else{
      this.setState({isInfiniteLoading: false});
    }
  };

  /**
   * 打开会话框
   */
  handleOpenChatDialog = (initData, index) => {
    let data = {
      friendId: initData.companion_id,
      friendName: initData.user_name,
      friendImg: initData.user_img,
      chatroomId: initData.chatroom
    };

    // 将有通知状态改为0
    let arr = this.state.data;
    arr[index].count_no_read_message = 0;

    // 传递数据至会话框
    this.setState({
      data: arr
    });

    // 加入房间
    this.chat.emit('join chatroom', initData.chatroom);

    this.props.actions.openMessageDialog(data);
  };

  // 关闭会话框
  handleCloseChatDialog = () => {
    this.props.actions.closeMessageDialog();
  };

  render() {
    let nullElement = (
      <Subheader>还没有好友，快去参加活动吧！</Subheader>
    );

    let elements = this.state.data.map((item, index) => {
      return (
        <div key={index} style={{width: '100%'}}>
          <Divider />
          <ListItem
            primaryText={item.user_name}
            leftAvatar={<Avatar src={item.user_img} />}
            rightIcon={
              <CommunicationChatBubble 
                color={item.count_no_read_message == 0 ? grey400 : this.props.color500}
              />
            }
            onClick={this.handleOpenChatDialog.bind(this, item, index)}
          />
        </div>
      )
    });
    
  	return (
  	  <div>
        <InfiniteScroll
          pageStart={0}
          loadMore={this.handleInfiniteLoad.bind(this)}
          hasMore={this.state.isInfiniteLoading}
          loader={this.elementInfiniteLoad()}
          initialLoad={false}
          useWindow={true}
          threshold={20}
        >
          <Card style={styles.box} className="col-md-6 col-sm-8 col-xs-12 center-block">
            <List>
              <Subheader>所有 {this.state.total}</Subheader>
              <Masonry
                className="center-block"
                style={{width: '100%'}}
                elementType={'div'}
              >
                {this.state.data.length === 0 ? nullElement : elements}
              </Masonry>
            </List>
          </Card>
        </InfiniteScroll>

        <Chat
          token={this.props.token}
          color500={this.props.color500}
          open={this.props.openMessageDialog}
          userId={this.props.userId}
          userName={this.props.userName}
          userImg={this.props.userImg}
          friendId={this.props.friendId}
          friendName={this.props.friendName}
          friendImg={this.props.friendImg}
          chatroomId={this.props.chatroomId}
          handleClose={this.handleCloseChatDialog}
          isSmallViewport={this.props.isSmallViewport}
          socket={this.props.socket}
        />
  	  </div>
  	);
  }
};

const styles = {
  box: {
    padding: 0,
    marginBottom: 24
  },
};

const mapStateToProps = (state) => ({
  friendId: state.message.friendId,
  friendName: state.message.friendName,
  friendImg: state.message.friendImg,
  chatroomId: state.message.chatroomId,
  openMessageDialog: state.message.openMessageDialog,
});

const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(actionCreators, dispatch)
});

export default connect(mapStateToProps, mapDispatchToProps)(Friends);